<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
	<title>群聊界面</title>
	<link rel="stylesheet" type="text/css" href="../css/api.css"/>
	<link rel="stylesheet" type="text/css" href="../css/style.css"/>
	<link rel="stylesheet" type="text/css" href="../css/message_list.css" />
	<!--<link rel="stylesheet" href="../js/libs/sui/sm.min.css">-->
	<link rel="stylesheet" href="../iconfont/iconfont.css">
	<link rel="stylesheet" href="../less/main.css"/>
	<style>
	</style>
</head>
<body>
<div id="tab1" class="content">
	<div class="head-no-toolbar bg-self-green no-left-icon">
		<span class="icon iconfont c-white p-l" onclick="javascript:closeWin();">&#xe61f;</span>
		<span id="class_name" class="c-white t-center"></span>
	</div>
	<div id="messageList">

	</div>
</div>
</body>
</html>
<script type="text/javascript" src="../js/api.js"></script>
<script type="text/javascript" src="../js/libs/jquery-3.1.0.min.js"></script>

<!--<script type='text/javascript' src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>-->
<script type="text/javascript">
	var Zepto = jQuery;
</script>
<script type='text/javascript' src='../js/libs/sui/sm.min.js' charset='utf-8'></script>
<script type='text/javascript' src='../js/libs/sui/sm-extend.min.js' charset='utf-8'></script>
<script src="../js/utils.js"></script>
<script src="../js/common.js"></script>

<!--<script type="text/javascript" src="script/jquery.lazyload.js"></script>-->
<script type="text/javascript">
	apiready = function() {

		var paraObj = api.pageParam;
		var staffObj = getLoginUserInfo();
		var studentObj = getLoginStudentInfo();

		if(isObject(paraObj) && isObject(staffObj) && isObject(studentObj)) {

			var studentPic;
			if (isEmpty(staffObj.PHOTO_PATH)) {
				studentPic = "../images/default-header.png";
			} else {
				studentPic = "{0}upload/{1}".format(getUrl(), staffObj.PHOTO_PATH);
			}
			var className = paraObj.className;
			var classId = paraObj.classId;
			var rongcloudToken = paraObj.rongcloudToken;
			var classMates = paraObj.classMates;
			$("#class_name").html(className);


			var fh = $(window).height();
			$('#tab1').height(fh).css({
				overflow : 'auto'
			})
			var UIChatBox = api.require('UIChatBox');
			// 懒加载图片
			//		$(function() {
			//			$("img.content-img").lazyload({
			//				effect : "fadeIn"
			//			});
			//		});
			UIChatBox.open({
				placeholder : '',
				maxRows : 4,
				emotionPath : 'widget://image/emotion',
				texts : {
					//				recordBtn : {
					//					normalTitle : '按住说话',
					//					activeTitle : '松开结束'
					//				},
					sendBtn : {
						title : '发送'
					}
				},
				styles : {
					inputBar : {
						borderColor : '#d9d9d9',
						bgColor : '#f2f2f2'
					},
					inputBox : {
						borderColor : '#B3B3B3',
						bgColor : '#FFFFFF'
					},
					emotionBtn : {
						normalImg : 'widget://image/face1.png'
					},
					extrasBtn : {
						normalImg : 'widget://image/add1.png'
					},
					keyboardBtn : {
						normalImg : 'widget://image/key1.png'
					},
					// 取消发送语音按钮
					//				speechBtn : {
					//					normalImg : 'widget://res/img/chatBox_key1.png'
					//				},
					//				recordBtn : {
					//					normalBg : '#c4c4c4',
					//					activeBg : '#999999',
					//					color : '#000',
					//					size : 14
					//				},
					indicator : {
						target : 'both',
						color : '#c4c4c4',
						activeColor : '#9e9e9e'
					},
					sendBtn : {
						titleColor : '#4cc518',
						bg : '#999999',
						activeBg : '#46a91e',
						titleSize : 14
					}
				},
				extras : {
					titleSize : 10,
					titleColor : '#a3a3a3',
					btns : [{
						title : '图片',
						normalImg : 'widget://image/album1.png',
						activeImg : 'widget://image/album1.png'
					}, {
						title : '拍照',
						normalImg : 'widget://image/chatBox_cam1.png',
						activeImg : 'widget://image/chatBox_cam1.png'
					}]
				}
			}, function(ret, err) {
				if (ret) {
					// 事件监听
					var eventType = ret.eventType;
					var msg = ret.msg;
					if ("send" == eventType) {
						// 发送消息
						sendTextMsg(msg);
						insert(msg,studentPic);
					} else if ("clickExtras" == eventType) {
						var index = ret.index;
						if (index == 0) {
							getPicture('album');
						} else if (index == 1) {
							getPicture('camera');
						}
					}
				} else {
					toast(JSON.stringify(err));
				}
			});
			//监听 inputBar
			UIChatBox.addEventListener({
				target : 'inputBar',
				name : 'move'
			}, function(ret, err) {
				//			alert(JSON.stringify(ret));
				if (ret) {
					var panelHeight = ret.panelHeight;
					var di = $('#tab1');
					var h = di.height();
					if (panelHeight != 0) {
						di.height(h - 276);
					} else {
						di.height(h + 276);
					}
					scrollView();
				} else {
					toast(JSON.stringify(err));
				}
			});
			var messageLis = $("#messageList");
			// 初始化聊天连接
			var rong = api.require('rongCloud2');
			rong.init(function(ret, err) {
				if (ret.status == 'success')
					api.toast({
						msg : '聊天服务器连接成功'
					});
			});
			// 连接聊天服务器
			rong.connect({
//			token : 'ogn4yAIWb9EbyxGr3ue50DvExgFH/XMrA2dfGCr6j2AkVI7uDcggiepbnV2mp6/CQvIyVXb9MwLf2QuxqJQPhoPWh6hEryrF'
				token : rongcloudToken
			}, function(ret, err) {
				if (ret.status == 'success') {
					/*api.toast({
						msg : ret.result.userId
					});*/
					synGroup();
				}
			});
			// 同步和创建群组
			function synGroup() {
				rong.syncGroup({
					groups : [{
						groupId : classId,
						groupName : className,
						portraitUrl : 'http://www.jx96166.com/uploads/allimg/140512/1331093140-1.jpg'
					}]
				}, function(ret, err) {
					if (ret.status == 'success')
//						joinGroup();
					gethistoryMsg();
					else
						api.toast({
							msg : err.code
						});
				})
			}

		/*	function joinGroup() {
				// 之前调用 init 和 connect 的代码省略
				rong.joinGroup({
					groupId: classId,
					groupName: className
				}, function(ret, err) {
					if (ret.status == 'success')

					else
						api.toast({ msg: err.code });
				})
			}
*/
			// 获取历史聊天记录 同步群组之后才能使用
			function gethistoryMsg() {
				rong.getHistoryMessages({
					conversationType : 'GROUP',
					targetId : classId,
					oldestMessageId : -1,
					count : 20
				}, function(ret, err) {
					var contens = ret.result;
//					alert(JSON.stringify(contens));
//					alert(JSON.stringify(classMates));
					// 判断方向
					for (var i = contens.length - 1; i >= 0; i--) {
						var data = contens[i];
						var messageDirection = data.messageDirection;
						var objectName = data.objectName;
						var content = data.content;

						var photoPath;
						for (var j =0; j < classMates.length; j++) {
							var data1 = classMates[j];
							if(data1.STUDENT_ID == data.senderUserId) {
								photoPath = data1.PHOTO_PATH;
//								break;
							}
						}

						if (objectName == 'RC:TxtMsg') {
							var text = content.text;
							if (messageDirection == 'SEND') {
								insert(text,photoPath);
							} else if (messageDirection == 'RECEIVE') {
								insertTxt(text,photoPath);
							}
						} else if (objectName == 'RC:ImgMsg') {
							var imageUrl = content.imageUrl;
							if (messageDirection == 'SEND') {
								insertImag(imageUrl, photoPath);
							} else if (messageDirection == 'RECEIVE') {
								insertGetImag(imageUrl,photoPath);
							}
						}

						/*$.each(classMates,function (index,eleObj) {
							if(eleObj.STUDENT_ID === data.senderUserId) {
								photoPath = eleObj.PHOTO_PATH;
							}



						});*/


					}
				})
			}

			// 设置自动监听接收信息
			rong.setOnReceiveMessageListener(function(ret, err) {
				var content = ret.result.message.content.text;
				// 判断消息类型
				var msgType = ret.result.message.objectName;
				if (msgType == 'RC:TxtMsg') {
					content = content.replace("\"", "");
					content = content.replace("\"", "");
					// 接收
					insertTxt(content, studentPic);
				} else if (msgType == 'RC:ImgMsg') {
					var msgContent = ret.result.message.content;
					var imageUrl = msgContent.imageUrl;
					insertGetImag(imageUrl,studentPic);
				}
			})
			// 通过融云发送文本聊天
			function sendTextMsg(msg) {
				rong.sendTextMessage({
					conversationType : 'GROUP',
					targetId :classId,
					text : msg,
					extra : ''
				}, function(ret, err) {
					//				if (ret.status == 'prepare')
					// 准备发送
					//				else if (ret.status == 'success')
					// 发送成功
					//					else if (ret.status == 'error')
					// 发送失败
				});
			}

			// 选取图片
			function getPicture(type) {
				UIChatBox.closeBoard();
				api.getPicture({
					sourceType : type,
					encodingType : 'jpg',
					mediaValue : 'pic',
					destinationType : 'url',
					allowEdit : false,
					quality : 70,
					//				targetWidth: 520,
					//              targetHeight: 540,
					saveToPhotoAlbum : false
				}, function(ret, err) {
					if (ret) {
						// 融云发送图片
						var rong = api.require('rongCloud2');
						var localImgUrl = ret.data;
						rong.sendImageMessage({
							conversationType : 'GROUP',
							targetId : classId,
							imagePath : ret.data,
							extra : ''
						}, function(ret, err) {
							if (ret.status == 'prepare') {
								// msg : JSON.stringify(ret.result.message)
							} else if (ret.status == 'progress') {
								// msg : ret.result.progress
							} else if (ret.status == 'success') {
								insertImag(localImgUrl,studentPic);
							} else if (ret.status == 'error') {
								// msg : err.code
							}
						});
					}
				});
			}

			// 插入发送聊天记录
			function insert(msg,path) {
				var insertText = "<div class=\"sender\"><div class=\"sender-avatar\"><img src=\"{0}\"  width=\"30\" height=\"30\"></div><div class=\"sender-cont\"><div class=\"right_triangle\"></div><span>";
				insertText = insertText + msg + "</span><div class=\"status\"><!--发送状态--></div></div></div>";

				insertText = insertText.format(path);
				messageLis.append(insertText);

				scrollView();
			}

			// 滑动底部
			function scrollView() {
				var h = $('#messageList').height();
				$('#tab1').scrollTop(h);
			}

			// 插入发送图片
			function insertImag(imgUrl,path) {
				var html = '<div class="sender">' + '<div class="sender-avatar">' + '<img src="{0}"  width="30" height="30">' + '</div>' + '<div class="sender-cont">' + '<div class="right_triangle"></div>' + '<img id="content-img" src="' + imgUrl + '" />' + '<div class="status">' + '</div>' + '</div>' + '</div>';

				html = html.format(path);
				messageLis.append(html);
				scrollView();
			}

			// 插入接收图片
			function insertGetImag(imgUrl,path) {
				var html = '<div class="receiver">' + '<div class="receiver-avatar">' + '<img src="{0}"  width="30" height="30">' + '</div>' + '<div class="receiver-cont">' + '<div class="left_triangle"></div>' + '<img id="content-img" src="' + imgUrl + '" />' + '<div class="status">' + '</div>' + '</div>' + '</div>';
				html = html.format(path);
				messageLis.append(html);
				scrollView();
			}

			// 插入接收文本信息
			function insertTxt(content,path) {
				var otherText = '<div class=\"receiver\">' + '<div class=\"receiver-avatar\">' + '<img src=\"{0}"  width=\"30\" height=\"30\">' + '</div>' + '<div class=\"receiver-cont\">' + '<div class=\"left_triangle\">' + '</div>' + '<span>' + content + '</span></div></div>';
				otherText = otherText.format(path);
				messageLis.append(otherText);
				scrollView();
			}



		}


	}
</script>